package com.corpdata.common.api.keyfree;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

public class GenerateUtil {

    private final static String APP_KEY = "mm4ccka5bbb4lloctqgygqcc";
    private static String APP_SECRET = "oy64dyvm9s0xzkyyuh4pb5ci2gnu3csh";

    /**
     * 生成秘钥
     *
     * @param type 默认3
     * @param life 有效期(秒)
     * @param phoneNumber 用户手机号
     * @return
     */
    public static String generate(Integer type, Integer life, String phoneNumber) {
        Date currentDate = new Timestamp(System.currentTimeMillis());
        Date expires = getPlugMinutes(currentDate, life / 60);

        StringBuilder builder = new StringBuilder();
        builder.append(type).append(life).append(expires.getTime()).append(phoneNumber).append(APP_KEY).append(APP_SECRET);

        String sign = encrypt256(builder.toString());

        StringBuilder tokenBuilder = new StringBuilder();
        tokenBuilder.append(APP_KEY).append("|").append(type).append(".").append(sign).append(".")
                .append(life).append(".").append(expires.getTime()).append("-").append(phoneNumber);

        return tokenBuilder.toString();
    }

    public static Date getPlugMinutes(Date currentDate, int minutes) {
        Calendar date = Calendar.getInstance();
        date.setTime(currentDate);
        date.set(Calendar.MINUTE, date.get(Calendar.MINUTE) + minutes);
        return date.getTime();
    }

    public static String encrypt256(final String strSrc) {
        MessageDigest md = null;
        String strDes = null;

        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-256");
            md.update(bt);
            // to HexString
            strDes = bytes2Hex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }

    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = Integer.toHexString(bts[i] & 0xFF);
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }
}
